package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.common.utils.StringUtils;
import com.heima.common.exception.CustomException;
import com.heima.file.service.impl.MinIOFileTemplate;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.baidu.Base64Util;
import com.heima.utils.baidu.FileUtil;
import com.heima.utils.baidu.HttpUtil;
import com.heima.wemedia.service.BaiduScanService;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Map;

/**
 * @Author Lijx
 * @Date 2024-07-23 10:32
 */
@Service
@Slf4j
public class BaiduScanServiceImpl implements BaiduScanService {

    @Autowired
    private MinIOFileTemplate minIOFileTemplate;
    @Autowired
    private Map<String,String> localCacheMap;

    public static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    @Override
    public Integer scanText(String text) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined";
        try {
            String param = "text=" + URLEncoder.encode(text, "utf-8");

//            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
//            String accessToken = "24.1f645252d5fea83c021fbdb5c44ce447.2592000.1724292630.282335-97738448";

            //先去缓存中取access_token
            String accessToken = localCacheMap.get("accessToken");
            //缓存中取不到，再调百度API获取access_token
            if (StringUtils.isEmpty(accessToken)){
                accessToken = getAccessToken();
                if (StringUtils.isNotEmpty(accessToken)){
                    //再将access_token添加到缓存
                    localCacheMap.put("accessToken",accessToken);
                }else {
                    throw new CustomException(AppHttpCodeEnum.BAIDU_ACCESS_ERROR);
                }
            }
            String result = HttpUtil.post(url, accessToken, param);
            Integer type = JSONObject.parseObject(result).getInteger("conclusionType");
            return type;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 4; //审核失败，转人工审核
    }

    @Override
    public Integer scanImg(String imgUrl) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/solution/v1/img_censor/v2/user_defined";
        try {
            //将网络图片地址转为字节数组
            byte[] imgData = minIOFileTemplate.downLoadFile(imgUrl);
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");

            String param = "image=" + imgParam;

//            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
//            String accessToken = "24.1f645252d5fea83c021fbdb5c44ce447.2592000.1724292630.282335-97738448";

            //先去缓存中取access_token
            String accessToken = localCacheMap.get("accessToken");
            //缓存中取不到，再调百度API获取access_token
            if (StringUtils.isEmpty(accessToken)){
                accessToken = getAccessToken();
                if (StringUtils.isNotEmpty(accessToken)){
                    //再将access_token添加到缓存
                    localCacheMap.put("accessToken",accessToken);
                }else {
                    throw new CustomException(AppHttpCodeEnum.BAIDU_ACCESS_ERROR);
                }
            }
            String result = HttpUtil.post(url, accessToken, param);
            Integer type = JSONObject.parseObject(result).getInteger("conclusionType");
            return type;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 4; //审核失败，转人工审核
    }

    public String getAccessToken() {
        try {
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, "");
            Request request = new Request.Builder()
                    .url("https://aip.baidubce.com/oauth/2.0/token?client_id=k2Hnppxkpbuj8E9vWnYhqRwv&client_secret=287BavSa0aHAI4NyZoMVEVgIaKaetS3W&grant_type=client_credentials")
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Accept", "application/json")
                    .build();
            Response response = HTTP_CLIENT.newCall(request).execute();
            String result = response.body().string();
            String accessToken = JSONObject.parseObject(result).getString("access_token");

            return accessToken;
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 定期清理本地缓存
     */
    @Scheduled(cron = "* * 0 1/15 * ?")
    @PostConstruct
    public void clearLocalCacheMap(){
        log.info("定时任务开启清理本地缓存...");
        localCacheMap.clear();
    }
}
